package com.polonium.pageobject.selenium;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

public class WebAppConfig {

	public static final String POLONIUM_PROPERTIES = "polonium.properties";

	public static final String POLONIUM_HOST = "polonium.host";
	public static final String POLONIUM_PORT = "polonium.port";
	public static final String POLONIUM_CONTEXT = "polonium.context";

	public static final String DEFAULT_POLONIUM_CONTEXT = "/";
	public static final String DEFAULT_POLONIUM_PORT = "8080";
	public static final String DEFAULT_POLONIUM_HOST = "http://localhost";

	private String context = DEFAULT_POLONIUM_CONTEXT;
	private String port = DEFAULT_POLONIUM_PORT;
	private String host = DEFAULT_POLONIUM_HOST;

	public WebAppConfig() {
		Properties properties = new Properties();
		FileInputStream inStream = null;
		try {
			URL url = ClassLoader.getSystemResource(POLONIUM_PROPERTIES);
			if (url == null) {
				throw new IOException();
			}
			inStream = new FileInputStream(new File(url.getFile()));
			properties.load(inStream);
			context = properties.getProperty(POLONIUM_CONTEXT, DEFAULT_POLONIUM_CONTEXT);
			port = properties.getProperty(POLONIUM_PORT, DEFAULT_POLONIUM_PORT);
			host = properties.getProperty(POLONIUM_HOST, DEFAULT_POLONIUM_HOST);
		} catch (IOException e) {
//			LOG.info("No properties file found");
		} finally {
			IOUtils.closeQuietly(inStream);
		}

		String systemHost = System.getProperty(POLONIUM_HOST);
		String systemPort = System.getProperty(POLONIUM_PORT);
		String systemContext = System.getProperty(POLONIUM_CONTEXT);
		if (systemHost != null) {
			host = systemHost;
		}
		if (systemPort != null) {
			port = systemPort;
		}
		if (systemContext != null) {
			context = systemContext;
		}

//		LOG.info("\nHost: {} \nPort: {} \nContext: {}", host, port, context);
	}

	public String getBaseUrl() {
		return host + (port == null ? "" : ":" + port) + context;
	}
}
